var RiseVision = RiseVision || {};
RiseVision.Common = RiseVision.Common || {};
RiseVision.Common.Sports = {};

RiseVision.Common.Sports = function(displayID) {
  var self = this;

  if (displayID) {
   this.displayID = displayID;
  }
  else {  //Use dummy ID.
   this.displayID = "xxx";
  }

  this.sport = prefs.getString("sport");
  this.collegeGames = prefs.getString("collegeGames");
  this.allSportsIndex = 0;
  this.updateInterval = 60000;
  this.allSports = ["NFL", "MLB", "NBA", "NHL", "CFOOT", "CBASK"];
  this.viz = new RiseVision.Common.Visualization();
}
RiseVision.Common.Sports.prototype.getData = function() {
  var self = this;

  this.wasReset = false;

  if (this.sport == "ALL") {
   this.processData("http://www.datacallrise.net/" + this.allSports[this.allSportsIndex] + this.getGroup() + ".php?" + "DisplayId=" + this.displayId, function() {
      self.onSportLoaded();
     });
  }
  else {
    var group = "";

    if ((this.sport == "CFOOT") || (this.sport == "CBASK")) {
      group = "&Group=" + this.collegeGames;
    }

    this.processData("http://www.datacallrise.net/" + this.sport + this.getGroup() + ".php?" + "DisplayId=" + this.displayID, function() {
        self.onDataLoaded();
      });
  }
}
RiseVision.Common.Sports.prototype.processData = function(url, callback) {
  var self = this;

  //Get sports data.
  $.ajax({
    url: url,
    success: function(data) {
      if (data) {
        var game = data.getElementsByTagName("Game"),
          sportCode = "", sportName, i;

        if (!self.wasReset) {
          self.sports = [];
          self.games = [];
          self.wasReset = true;
        }

        if (data) {
          if (data.getElementsByTagName("Sport").length > 0) {
            sportCode = data.getElementsByTagName("Sport")[0].getAttribute("Code");
          }

          if (game.length > 0) {
            sportName = self.getNodeValue(data.getElementsByTagName("Title"));

            self.sports.push({
              sportCode: sportCode,
              name: sportName
            });
          }

          //Get game stats.
          for (i = 0; i < game.length; i++) {
            var status = "",
              extendedStatus = "",
              team = game[i].getElementsByTagName("Team"),
              overUnder = "",
              host, visitor, home, j, date;

            if (game[i].getElementsByTagName("Status").length > 0) {
              var statusEle = game[i].getElementsByTagName("Status")[0];
              //status = game[i].getElementsByTagName("Status")[0].getAttribute("Code");
              status = statusEle.getAttribute("Code");
              extendedStatus = statusEle.getAttribute("Code");
              if(status == "Pre-Game") {
                status = "not started";
                extendedStatus = self.getNodeValue(game[i].getElementsByTagName("Time"));
              } else if(status == "In-Progress")  {
                if (sportCode == "MLB") {
              	  extendedStatus =  statusEle.getElementsByTagName("Inning")[0].getAttribute("Segment") + " " + statusEle.getElementsByTagName("Inning")[0].getAttribute("Number") + " Inning";
                } else if (sportCode == "NHL" || sportCode == "NBA") {
              	  extendedStatus =  "Period " + self.getNodeValue(statusEle.getElementsByTagName("Period"));
                }             
              }

            }
            
            overUnder = "O/U " + self.getNodeValue(game[i].getElementsByTagName("OverUnder"));
            date = self.getNodeValue(game[i].getElementsByTagName("Date"));

            if (date) {
              date = Date.parse(date);
            }

            for (j = 0; j < team.length; j++) {
              host = team[j].getAttribute("Host");

              if (host == "Visiting") {
                console.log("got visiting team");
                visitor = self.getTeamInfo(team[j], sportCode);
              }
              else if (host == "Home") {
                console.log("got home team");
                home = self.getTeamInfo(team[j], sportCode);
              }
            }

            self.games.push({
              sportCode: sportCode,
              date: date,
              status: status,
              extendedStatus: extendedStatus,
              overUnder: overUnder,
              visitor: visitor,
              home: home
            });
          }

          callback();
        }
        else {
          console.log("Invalid data source URL");
        }
      }
      else {
        setTimeout(function() {
          $(self).trigger("updateTimerExpired");
        }, self.updateInterval);
      }
    },
    dataType: "xml"
  });
}
RiseVision.Common.Sports.prototype.onSportLoaded = function() {
  var self = this, group;

  this.allSportsIndex++;

  group = this.getGroup();

  if (this.allSportsIndex == this.allSports.length) { //All games for all sports have been loaded.
    this.allSportsIndex = 0;
    this.onDataLoaded();
  }
  else {  //Load games for next sport.
    this.processData("http://www.datacallrise.net/" + this.allSports[this.allSportsIndex] + this.getGroup() + ".php?" + "DisplayId=" + this.displayId, function() {
        self.onSportLoaded();
      });
  }
}
RiseVision.Common.Sports.prototype.getGroup = function() {
  var group = "";

  if ((this.allSports[this.allSportsIndex] == "ALL") || (this.allSports[this.allSportsIndex] == "CFOOT") || (this.allSports[this.allSportsIndex] == "CBASK")) {
    if(this.collegeGames == "AP" )  group = "25";
  }

  return group;
}
RiseVision.Common.Sports.prototype.getTeamInfo = function(team, sportCode) {
  
  return {
    name: this.getNodeValue(team.getElementsByTagName("Team")),
    rank: this.getNodeValue(team.getElementsByTagName("Rank")),
    overall: this.getNodeValue(team.getElementsByTagName("Overall")),
    score: this.getNodeValue(team.getElementsByTagName("Total")),
    spread: this.getNodeValue(team.getElementsByTagName("Spread"))
  };
}
RiseVision.Common.Sports.prototype.getNodeValue = function(node) {
  if (node.length > 0) {
    if (node[0].childNodes.length > 0) {
      return node[0].childNodes[0].nodeValue;
    }
    else {
      return "";
    }
  }

  return "";
}
RiseVision.Common.Sports.prototype.onDataLoaded = function() {
  var self = this;

  if (this.sports.length === 0) {
    $(this).trigger("noData");
  }
  else {
    setTimeout(function() {
      $(self).trigger("updateTimerExpired");
    }, this.updateInterval);

    $(this).trigger("imagesLoaded");
  }
}